// home_spk/pages/good_detail/index.js
const app = getApp()
Page({
  data: {
    goodsDetail: {}
  },
  onLoad({ goods_id }) {
    this.getGoodsDetail(goods_id)
  },
  async getGoodsDetail(goods_id) {
    const { message, meta } = await wx.http.get('/api/public/v1/goods/detail', {
      goods_id
    })
    if (meta.status !== 200) wx.utils.toast('获取商品详情失败！')
    this.setData({
      goodsDetail: message
    })
  },
  switchTab({ mark: { url } }) {
    wx.reLaunch({
      url
    })
  },
  addCar() {
    const { goods_id, goods_big_logo, goods_name, goods_price } = this.data.goodsDetail
    if (!app.car.some(item => item.goods_id === goods_id)) {
      app.car.unshift({
        goods_id,
        goods_big_logo,
        goods_name,
        goods_price,
        num: 1,
        checked: false
      })
      wx.setStorageSync('car', JSON.stringify(app.car))
      wx.utils.toast('已加入购物车')
      return
    }
    app.car = app.car.map((item) => {
      if (item.goods_id === goods_id) item.num++
      return item
    }
    )
    wx.setStorageSync('car', JSON.stringify(app.car))
    wx.utils.toast('已加入购物车')
  }
})